<!-- 系统管理-能源种类菜单管理 -->
<script setup lang="ts">
import { Delete, Edit } from '@element-plus/icons-vue'
import type { Action } from 'element-plus'
import { ElTree } from 'element-plus'
import { FormModal, SearchForm } from './components'
import {
  defaultFormData,
  defaultPagingParams,
} from './index'
import { ENERGY } from '@/constant'
import type { TableColumn } from '@/types'
// ------------------use------------------
// #region
const { globalProperties, $confirm, $message }
  = useCurrentInstance()
const { withLoading, loading, vLoading }
  = useDefineLoading()
const [tableData, setTableData] = useState<any[]>([])
const [formData, setFormData] = useState<any>({
  ...defaultFormData,
})
const [total, setTotal] = useState<number>(0)
const [formModalTitle, setFormModalTitle]
  = useState<string>('')
const [isEdit, setIsEdit] = useState<boolean>(false)
const [treeData, setTreeData] = useQuoteState<any[]>([])
// #endregion
// ------------------静态变量------------------
// #region
const columns: TableColumn<any>[] = [
  {
    key: uuid(),
    type: 'index',
    width: '80',
    label: '序号',
  },
  {
    key: uuid(),
    label: '名称',
    render() {
      return '名称'
    },
  },
]
const defaultProps = {
  children: 'children',
}
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const pagingParams = ref({
  ...defaultPagingParams,
})
const filterTextInput = ref<string>('')
const modalRef = ref<InstanceType<typeof FormModal>>()
const treeRef = ref<InstanceType<typeof ElTree>>()
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region
// #endregion
// ------------------生命周期------------------
// #region
onMounted(() => {
  getTableData()
  getTreeData()
})
// #endregion
// ------------------内置方法---------------------
// #region
watch(
  () => filterTextInput.value,
  (val: string) => {
    treeRef.value?.filter?.(val)
  },
)
// #endregion
// ------------------方法---------------------
// #region
async function getTreeData() {
  await withLoading(nextTick, 'tree')()
  setTreeData(ENERGY.typeList as any)
}
async function deleteData(id: number) {
  const res: Action = await $confirm(
    '该操作将永久删除该数据，确定删除？',
    '警告',
    {
      type: 'warning',
    },
  ).catch(e => e)

  if (res !== 'confirm')
    return
  globalProperties.$message.success(
    `${id ?? ''}删除成功！`,
  )
  getTableData()
}
async function showEditDialog(row: any) {
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('编辑')
  setIsEdit(true)
  setFormData({ ...defaultFormData, ...row })
}
async function showAddDialog() {
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('新增')
  setIsEdit(false)
  setFormData({ ...defaultFormData })
}
async function getTableData() {
  await withLoading(sleep)(1000)

  setTotal(30)
  setTableData([])
}
async function addOrUpdateData(row: any) {
  await sleep(1000)
  getTableData()
  globalProperties.$message.success(
    `${row.id ?? ''}数据更新成功！`,
  )
}
function addData() {
  addOrUpdateData(formData.value)
  modalRef.value?.close()
  $message.success('保存成功！')
}
function editData() {
  addOrUpdateData(formData.value)
  modalRef.value?.close()
  $message.success('保存成功！')
}
function handleSaveSuccess() {
  isEdit.value ? editData() : addData()
}
function filterNode(value: string, data: any) {
  if (!value)
    return true
  return data?.label?.includes?.(value)
}
// #endregion
</script>

<template>
  <div
    class="padding-sm align-center flex gap-sm container"
  >
    <div
      v-loading
      class="container-left height-fill flex-incompressible padding-sm flex-direction box-border flex gap-xs"
    >
      <h5 class="flex-incompressible margin-0">
        字典分组
      </h5>
      <el-input
        v-model="filterTextInput"
        placeholder="关键字"
        class="flex-incompressible"
      />
      <ElTree
        ref="treeRef"
        class="flex-fillRemaining"
        :data="treeData"
        :props="defaultProps"
        accordion
        highlight-current
        default-expand-all
        :filter-node-method="filterNode"
        @contextmenu.prevent
      />
    </div>
    <div
      class="height-fill flex-fillRemaining flex-direction overflow box-border flex align-end"
    >
      <view-table
        :loading="loading"
        :columns="columns"
        :data="tableData"
      >
        <template #actions>
          <SearchForm
            v-model="pagingParams"
            @search="getTableData"
            @reset="getTableData"
            @plus="showAddDialog"
          />
        </template>
        <template #operate="{ row }">
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="primary"
              :icon="Edit"
              @click="showEditDialog(row)"
            />
          </el-tooltip>
          <el-divider direction="vertical" />
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="danger"
              :icon="Delete"
              @click="deleteData(row.id)"
            />
          </el-tooltip>
        </template>
      </view-table>

      <!-- 分页 -->
      <ListsPagination
        v-model:page-num="pagingParams.pageNumber"
        v-model:page-size="pagingParams.pageSize"
        :total="total"
        @current-change="getTableData"
        @size-change="getTableData"
      />
    </div>
    <FormModal
      ref="modalRef"
      :title="formModalTitle"
      :data="formData"
      @save-success="handleSaveSuccess"
    />
  </div>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
.container {
  --container-lw: 300px;
  &-left {
    background-color: var(--el-bg-color);
    border: 1px solid var(--el-border-color-light);
    border-radius: 4px;
    width: var(--dictionary-lw);
    transition: all var(--motion-bezier) 0.3s;
    &:hover {
      box-shadow: 0 8px 32px #0000000d;
    }

    h5 {
      color: var(--el-text-color-primary);
    }
  }
}
//-------------样式穿透-------------
</style>
